//
//  HWTweetDBTool.m
//  HomeWork
//
//  Created by apple on 2017/10/25.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "HWTweetDBTool.h"
#import <FMDB/FMDB.h>

#define filename [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"tweetData.sqlite"]
@implementation HWTweetDBTool
static FMDatabaseQueue *_queue;

+ (void)initialize{
    
  
    _queue = [FMDatabaseQueue databaseQueueWithPath:filename];
    
    
    [_queue inDatabase:^(FMDatabase *db) {
        
        // id 主键  errorData 是否错误数据  tweetInfo 数据（二进制） reserve1-4 预留字段
        BOOL result = [db executeUpdate:[NSString stringWithFormat:@"create table if not exists t_tweetData (id integer primary key autoincrement, errorData text, tweetInfo blob, reserve1 text, reserve2 text, reserve3 text, reserve4 text);"]];
        
        if (result) {
            HWLog(@"创表成功");
            
        } else {
            HWLog(@"创表失败");
        }
    }];
    [self deleteAllTweets];
}

+ (void)saveTweet:(HWTweetsModel *)model{
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        NSData *tweetInfo = [NSKeyedArchiver archivedDataWithRootObject:model];
        
        //添加更新数据
        NSString *strSql1 = [NSString stringWithFormat:@"insert into t_tweetData(errorData,tweetInfo)values(?,?);"];
        BOOL result = [db executeUpdate:strSql1,  @"0", tweetInfo];
        
        if(!result){
            *rollback = YES;
        }
    }];
}

+ (NSArray *)getTweetWithIndex:(NSInteger)index pageSize:(NSInteger)pageSize{
    
    NSMutableArray *tweets = [NSMutableArray array];
    
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        NSString *strSql = [NSString stringWithFormat:@"select * from t_tweetData limit %ld, %ld;", index * pageSize, pageSize];
        
        FMResultSet *set = [db executeQuery:strSql];
        while ([set next]) {
            NSData *tweetInfo = [set dataForColumn:@"tweetInfo"];
            HWTweetsModel *tweet = [NSKeyedUnarchiver unarchiveObjectWithData:tweetInfo];
            if (tweet) {
                [tweets addObject:tweet];
            }
        }
    }];
    return tweets;
}

+ (void)deleteAllTweets{
    [_queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        NSString *strSql = [NSString stringWithFormat:@"delete from t_tweetData;"];
        
        BOOL result = [db executeUpdate:strSql];
        
        if(!result){
            *rollback = YES;
        }
    }];

}

@end
